import { createRouter, createWebHistory } from "vue-router";
import store from "@/store";
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/login",
      name: "login",
      meta: {
        label: "登录",
        isKeep: true, //用来给removeRoute做识别的
      },
      component: () => import("../views/login/index.vue"),
    },
    {
      path: "/",
      name: "index",
      meta: {
        label: "后台管理系统",
        isKeep: true, //用来给removeRoute做识别的
      },
      component: () => import("../views/layout.vue"),
      redirect: "/dashboard/console",
      children: [
        {
          path: "/403",
          name: "403",
          meta: {
            isKeep: true, //用来给removeRoute做识别的
          },
          component: () => import("../views/error/403.vue"),
        },
      ],
    },
    {
      path: "/:pathMatch(.*)*",
      name: "404",
      meta: {
        isKeep: true, //用来给removeRoute做识别的
      },
      component: () => import("../views/error/404.vue"),
    },
  ],
});

//白名单路由集合
const whiteNames = ["login"];
router.beforeEach(async (to, from) => {
  //非白名单路由
  if (!whiteNames.includes(to.name)) {
    //不在白名单,做登录校验
    //获取user仓库中的token
    const token = store.state.user.token;
    if (!token) {
      //跳转到登录界面
      return {
        name: "login",
        query: {
          redirect: to.fullPath,
        },
      };
    }
    //获取当前是否动态添加过
    const isAdd = store.state.user.isAdd;
    if (!isAdd) {
      // 0.修改isAdd为true
      store.commit("user/setIsAdd", true);
      // 1.获取用户个人信息,并返回用户权限
      const routes = await store.dispatch("user/getInfo");
      // 2.动态添加路由
      routes.forEach((route) => {
        router.addRoute("index", {
          path: route.router,
          name: route.router,
          meta: {
            label: route.name,
          },
          component: () => import(`../${route.viewPath}`),
        });
      });
      //3.重定向
      return to.fullPath;
    }
  }
});

//切换网页标题
router.afterEach((to, from) => {
  document.title = "个人后台管理系统_" + to.meta.label;
});
export default router;
